SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ConsecutiveBanks]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)

CREATE TABLE [dbo].[ConsecutiveBanks](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](40) NOT NULL,
	[CurrentConsecutive] [int] NOT NULL,
 CONSTRAINT [PK_ConsecutiveBanks] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

-- =============================================
-- Author:		Jaime Alberto Jaramillo Zapata
-- Create date: Jun 25th, 2012
-- Description:	Adds a new DocumentID bank to the documentid application service database
-- =============================================
CREATE PROCEDURE USP_AddDocumentIDBank 
	@bankName NVARCHAR(40)	
AS
BEGIN
	SET NOCOUNT ON;
	INSERT INTO ConsecutiveBanks(Name, CurrentConsecutive) VALUES (@bankName, 1)
END
GO

-- =============================================
-- Author:		Jaime Alberto Jaramillo Zapata
-- Create date: June 25th, 2012
-- Description:	Deletes a DocumentID Bank from the documentid application service database
-- =============================================
CREATE PROCEDURE USP_DeleteDocumentIDBank 
	@bankName AS NVARCHAR(40)
AS
BEGIN
	SET NOCOUNT ON;

    DELETE FROM ConsecutiveBanks WHERE
    Name = @bankName
END
GO

-- =============================================
-- Author:		Jaime Alberto Jaramillo Zapata
-- Create date: June 25th, 2012
-- Description:	Resets a DocumentID Bank from the documentid application service database
-- =============================================
CREATE PROCEDURE USP_ResetDocumentIDBank
	@bankName AS NVARCHAR(50)
AS
BEGIN
	SET NOCOUNT ON;
	UPDATE ConsecutiveBanks
	SET 
		CurrentConsecutive = 1
	WHERE
		Name = @bankName
END
GO

-- =============================================
-- Author:		Jaime Alberto Jaramillo Zapata
-- Create date: June 25th, 2012
-- Description:	Fetchs the next available DocumentID fro, a given DocumentID Bank, from the documentid application service database
-- =============================================
CREATE PROCEDURE USP_GetNextDocumentID 
	@bankName AS NVARCHAR(40), 
	@currentConsecutive AS INTEGER OUT
AS
BEGIN
	SET NOCOUNT ON;
	SELECT 
		@currentConsecutive = CurrentConsecutive
	FROM
		ConsecutiveBanks
	WHERE
		Name = @bankName
		
	UPDATE ConsecutiveBanks
	SET
		CurrentConsecutive = @currentConsecutive+1
	WHERE
		Name = @bankName
END
GO